/**
 * vim: tabstop=4
 * 
 * @license		http://www.gnu.org/licenses/gpl.html GPL Version 3
 * @author		Ian Moore <imooreyahoo@gmail.com>
 * @copyright	Copyright (c) 2011 Ian Moore
 * @version		$Id: localnotifications.js 81 2011-12-13 18:25:04Z imooreyahoo@gmail.com $
 *
 * This file is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This file is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this file. If not, see <http://www.gnu.org/licenses/>.
 */
// require("js/omv/NavigationPanel.js")
// require("js/omv/data/DataProxy.js")
// require("js/omv/grid/GridPanel.js")
// require("js/omv/grid/TBarGridPanel.js")
// require("js/omv/util/Format.js")
// require("js/omv/module/admin/Notification.js")

Ext.ns("OMV.Module.System");


/**
 * Notification task to update menu with unread message count
 */
OMV.Module.System.LocalNotificationsTask = {
	
	// This will not exist until everything is rendered
	_targetNode : null,
	
	run: function(){

		OMV.Ajax.request(function(id, response, error) {
			
			if (error === null) {
				
				// This may fail if it has not been rendered yet
				try {
					if(!this._targetNode) {
						this._targetNode = Ext.ComponentMgr.get("west-panel").get(0).getRootNode().findChild("text","System").findChild("text","Notification");
					}
					this._targetNode.setText('Notifications' + (response.unreadcount > 0 ? ' <b>('+response.unreadcount+')</b>' : '' ));
				} catch (err) {
					// Fail silently
                }
				
			} else {
				OMV.MessageBox.error(null, error);
			}
			
		}, this, "LocalNotifications", "getUnreadCount", [ ]);

	},
	interval: 10000 // 10 seconds
};


/**
 * @class OMV.Module.System.LocalNotifications
 * 
 * Notifications list
 * 
 */

OMV.Module.System.LocalNotifications = function(config) {

		var initialConfig = {
			layout: {
				type: 'border'
			},
			// Change title else we end up with "System | Notificaions (X)"
			listeners: {
				beforerender: function() {
					this.findParentByType("panel").getTopToolbar().get(0).setText('System | Notifications');
				},
				scope: this
			},
			items: [{
				xtype: 'grid',
				title: 'Notifications',
				id: 'OMV.Module.System.LocalNotifications-grid',
				region: 'north',
				stripeRows: true,
				split: true,
				stateful: true,
				loadMask: true,
				height: (0.5 * Ext.lib.Dom.getViewHeight())-150,
				viewConfig: {
					forceFit: true
				},
				sm : new Ext.grid.RowSelectionModel({
					listeners: {
						selectionchange : this.selectionChange,
						scope: this
					}
				}),
				store : new OMV.data.Store({
					autoLoad: true,
					remoteSort: false,
					proxy: new OMV.data.DataProxy("LocalNotifications", "getMessages", [], false),
					reader: new Ext.data.JsonReader({
						idProperty: "uuid",
						totalProperty: "total",
						root: "data",
						fields: [
							{ name: "date" },
							{ name: "uuid" },
							{ name: "unread" },
							{ name: "subject" },
							{ name : "contentType" }
						 ]
					})
				}),

				columns: [{
					header: "Date",
					sortable: true,
					dataIndex: "date",
					width: 20,
					renderer: function(value, metaData, record, rowIndex, colIndex, store) {
						value = OMV.util.Format.localeTimeRenderer()(value, metaData, record, rowIndex, colIndex, store);
						if(record.get('unread'))
							return '<b>' + value + '</b>';
						return value;
					}
				},{
					header: "Subject",
					sortable: true,
					dataIndex: "subject",
					renderer: function(value, metaData, record) {
						if(record.get('unread'))
							return '<b>' + value + '</b>';
						return value;
					}
				}]
			},{
				xtype: 'panel',
				title: 'Details',
				id: 'OMV.Module.System.LocalNotifications-body',
				region: 'center',
				split: true,
				autoScroll: true,
				html: ''
			}]
		};
		
		Ext.apply(initialConfig, config);
		OMV.Module.System.LocalNotifications.superclass.constructor.call(
		  this, initialConfig);
};

Ext.extend(OMV.Module.System.LocalNotifications, Ext.Panel, {

	initComponent : function() {
		 OMV.Module.System.LocalNotifications.superclass.initComponent.
				  apply(this, arguments);
	},

	tbar: [{
		xtype: "button",
		text: "Refresh",
		icon: "images/reload.png",
		handler: function() {
			Ext.getCmp('OMV.Module.System.LocalNotifications-grid').getStore().reload();
		}
	},{
		xtype: 'tbseparator'
	},{
		xtype: "button",
		text: "Delete",
		id: 'OMV.Module.System.LocalNotifications-grid-delete',
		icon: "images/delete.png",
		disabled: true,
		handler: function() {
			
			var deleteCb = this.ownerCt.ownerCt.deleteMessages;

			Ext.MessageBox.show({
				title: "Confirmation",
				msg: "Are you sure you want to delete the selected notification(s)?",
				buttons: Ext.MessageBox.YESNO,
				fn: function(answer) {
					if (answer == "no")
						return;
					deleteCb();
				},
				scope: this,
				icon: Ext.MessageBox.QUESTION
			});

		}
	}],
	
	/**
	 * Delete selected message(s)
	 */
	deleteMessages: function() {

		var uuids = new Array();
		
		var sels = Ext.getCmp('OMV.Module.System.LocalNotifications-grid').getSelectionModel().getSelections();
		
		for(var i = 0; i < sels.length; i++) {
			uuids[uuids.length] = sels[i].get('uuid');
		}
		
		if(!uuids.length) return;
		
		OMV.Ajax.request(function(id, response, error) {
		
			if (error === null) {
				
				var grid = Ext.getCmp('OMV.Module.System.LocalNotifications-grid');
				grid.getStore().reload();
				
				grid.getSelectionModel().clearSelections(true);
				Ext.getCmp('OMV.Module.System.LocalNotifications-body').update('');
				
				// Re-get unread message count after delete
				OMV.Module.System.LocalNotificationsTask.run();
				
			} else {
				OMV.MessageBox.error(null, error);
			}
			
		}, this, "LocalNotifications", "deleteMessages", [ uuids ]);
		
	},
	
	/**
	 * Mark the selected message as read
	 */
	markRead: function(uuid) {
		
		OMV.Ajax.request(function(id, response, error) {
		
			if (error === null) {
				Ext.getCmp('OMV.Module.System.LocalNotifications-grid').getStore().getById(uuid).set('unread', 0);
				OMV.Module.System.LocalNotificationsTask.run();
			} else {
				OMV.MessageBox.error(null, error);
			}
			
		}, this, "LocalNotifications", "markRead", [ uuid ]);
		
	},
	
	/**
	 * Called when grid selection changes
	 */
	selectionChange: function(sm) {
		
		var records = sm.getSelections();
		
		if(records.length == 1) {
			
			Ext.getCmp('OMV.Module.System.LocalNotifications-grid-delete').enable();
			
			var uuid = records[0].get("uuid");
			var unread = records[0].get('unread');
			var useHtml = records[0].get('contentType').search(/html/i) > -1;
			
			OMV.MessageBox.wait(null, "Retreiving notification...");
			
			OMV.Ajax.request(function(id, response, error) {
				
				OMV.MessageBox.updateProgress(1);
				OMV.MessageBox.hide();
				
				if (error === null) {
					
					
					Ext.getCmp('OMV.Module.System.LocalNotifications-body').update('<div style="padding: 10px">' +
						(useHtml ? '' : '<pre>' ) + response.body + (useHtml ? '' : '</pre>') + '</div>');
					
					if(unread)
						this.markRead(uuid)
					
					
				} else {
					OMV.MessageBox.error(null, error);
				}
				
			}, this, "LocalNotifications", "getMessage", [ uuid ]);
		
		} else if(records.length > 0) {
			Ext.getCmp('OMV.Module.System.LocalNotifications-grid-delete').enable();
			Ext.getCmp('OMV.Module.System.LocalNotifications-body').update(records.length + ' selected');
		} else {
			Ext.getCmp('OMV.Module.System.LocalNotifications-grid-delete').disable();
			Ext.getCmp('OMV.Module.System.LocalNotifications-body').update('');
		}
	}


});

/*
 * Register panel overwriting existing notification panel
*/
OMV.NavigationPanelMgr.registerPanel("system", "notification", {
	cls: OMV.Module.System.LocalNotifications,
	title: "Notifications"
});



// Update notification count
var runner = new Ext.util.TaskRunner();
runner.start(OMV.Module.System.LocalNotificationsTask);

